#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-07
"""

import rpyc
from rpyc.utils.server import ThreadedServer
import logging
from apscheduler.schedulers.background import BackgroundScheduler

import time
import logging

log = logging.getLogger('apscheduler.executors')
log.setLevel(logging.INFO)  # DEBUG
fmt = logging.Formatter('%(levelname)s:%(message)s')
h = logging.StreamHandler()
h.setFormatter(fmt)
log.addHandler(h)

logging.basicConfig(
    format="%(asctime)s %(name)s[%(module)s#%(lineno)d] %(levelname)s %(message)s",
    level=logging.INFO)


def print_text(text):
    # fmt = logging.Formatter('%(levelname)s:{}%(message)s'.format(text))
    # h = logging.StreamHandler()
    # h.setFormatter(fmt)
    # log.addHandler(h)
    from mmonitor.models.mysql_db import TestModel
    TestModel.create(**{"msg": "%s: 执行任务: %s" % (time.asctime(), text)})
    # print("%s: 执行任务: %s" % (time.asctime(), text))
    logging.warning("执行任务: %s" % (text))


class SchedulerService(rpyc.Service):
    def exposed_add_job(self, func, *args, **kwargs):
        return scheduler.add_job(func, *args, **kwargs)

    def exposed_modify_job(self, job_id, jobstore=None, **changes):
        return scheduler.modify_job(job_id, jobstore, **changes)

    def exposed_reschedule_job(self, job_id, jobstore=None, trigger=None, **trigger_args):
        return scheduler.reschedule_job(job_id, jobstore, trigger, **trigger_args)

    def exposed_pause_job(self, job_id, jobstore=None):
        return scheduler.pause_job(job_id, jobstore)

    def exposed_resume_job(self, job_id, jobstore=None):
        return scheduler.resume_job(job_id, jobstore)

    def exposed_remove_job(self, job_id, jobstore=None):
        scheduler.remove_job(job_id, jobstore)

    def exposed_get_job(self, job_id):
        return scheduler.get_job(job_id)

    def exposed_get_jobs(self, jobstore=None):
        return scheduler.get_jobs(jobstore)


if __name__ == '__main__':
    from apscheduler.schedulers.background import BackgroundScheduler
    from apscheduler.jobstores.memory import MemoryJobStore
    from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
    from sqlalchemy import create_engine
    from mmonitor.common.config import mysql_db, mysql_password, mysql_server, mysql_user, mysql_port, rpc_port, rpc_host

    mysql_url = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (mysql_user,
                                                                 mysql_password,
                                                                 mysql_server,
                                                                 mysql_port,
                                                                 mysql_db)
    jobstores = {
        'default': SQLAlchemyJobStore(engine=create_engine(mysql_url,
                                                           encoding='utf-8',
                                                           pool_recycle=10,
                                                           echo=False))
    }
    scheduler = BackgroundScheduler(
        timezone='Asia/Shanghai',
        jobstores=jobstores,
        job_defaults=dict(misfire_grace_time=24 * 3600))

    scheduler.start()
    protocol_config = {'allow_public_attrs': True}
    server = ThreadedServer(SchedulerService, hostname="127.0.0.1", port=123, protocol_config=protocol_config)
    try:
        server.start()
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        scheduler.shutdown()